<template>
  <div class="ticket-list-container">
    <!-- <h1>车票列表</h1> -->
    <el-row>
      <el-col :span="16">
        <el-form :inline="true" :model="queryForm" class="demo-form-inline">
          <el-form-item label="出发地点">
            <el-input v-model="queryForm.departure" placeholder="请输入地点"></el-input>
          </el-form-item>
          <el-form-item label="到达地点">
            <el-input v-model="queryForm.arrival" placeholder="请输入地点"></el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="getTableData">查询</el-button>
          </el-form-item>
        </el-form>
      </el-col>

      <el-col :span="8" style="text-align: right;">
        <el-button-group>
          <el-button type="primary" @click="openDialog">新增</el-button>
          <el-button type="primary" @click="getOne">修改</el-button>
          <el-button type="primary" @click="delTicket">删除</el-button>
        </el-button-group>
      </el-col>
    </el-row>

    <el-row>
      <el-col :span="24">
        <el-table
          ref="multipleTable"
          :data="ticketList"
          tooltip-effect="dark"
          style="width: 100%"
          height="365px"
          border
          stripe
          @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" width="55"></el-table-column>
          <el-table-column type="index" label="序号" width="50" align="center"></el-table-column>
          <el-table-column label="出行类型" min-width="90" align="center">
            <template slot-scope="scope">{{ scope.row.type }}</template>
          </el-table-column>
          <el-table-column label="出发地" min-width="70" align="center">
            <template slot-scope="scope">{{ scope.row.departure }}</template>
          </el-table-column>
          <el-table-column label="到达地" min-width="70" align="center">
            <template slot-scope="scope">{{ scope.row.arrival }}</template>
          </el-table-column>
          <el-table-column label="出发时间" min-width="110" align="center">
            <template slot-scope="scope">{{ formatDate(scope.row.startTime) }}</template>
          </el-table-column>
          <el-table-column label="到达时间" min-width="110" align="center">
            <template slot-scope="scope">{{ formatDate(scope.row.endTime) }}</template>
          </el-table-column>
          <el-table-column label="金额" min-width="60" align="right">
            <template slot-scope="scope">{{ scope.row.price }}</template>
          </el-table-column>
          <el-table-column label="交通工具" min-width="100" align="center">
            <template slot-scope="scope">{{ getTransportName(scope.row.way) }}</template>
          </el-table-column>
          <el-table-column label="关联报销单号" min-width="160" align="right">
            <template slot-scope="scope">
            <span v-if="scope.row.travelId == 0">未绑定</span>
            <a
              v-else
              href="javascript:void(0)"
              @click="openTravelDetail(scope.row.travelId)"
              style="color: #409EFF; text-decoration: underline; cursor: pointer;"
            >
              {{ scope.row.travelId }}
            </a>
          </template>
          </el-table-column>
          <el-table-column label="操作" min-width="180" align="center">
            <template slot-scope="scope">
              <!-- 修改按钮 -->
              <el-button 
                size="mini" 
              type="primary" 
                @click="handleEdit(scope.row)"
              style="margin-right: 5px;"
              >
                修改
            </el-button>
            <!-- 删除按钮 -->
            <el-button 
                size="mini" 
                type="danger" 
                @click="handleDelete(scope.row)"
              >
                删除
            </el-button>
          </template>
          </el-table-column>
        </el-table>

        <el-pagination
          background
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :page-sizes="[6, 8, 10]"
          :page-size="queryForm.limit"
          layout="prev, pager, next, total, sizes, jumper"
          :total="total"
        ></el-pagination>
      </el-col>
    </el-row>

    <ticket-info :isShow="visible" :transData="transList" :ticketInfo="ticketForm" @closeDialog="visible = false" @ticketSave="tableLoad"></ticket-info>

    <travel-info
      :isShow="visible2"
      :travelInfo="travelForm"
      @closeDialog="visible2 = false"
      @travelSave="tableLoad"
      >
    </travel-info>

  </div>
</template>

<script>
import TicketInfo from '@/components/TicketInfo.vue';
import TravelInfo from '@/components/TravelInfo.vue';

export default {
  name: 'TicketList',
  components: {
    TicketInfo,
    TravelInfo
  },
  data() {
    return {
      ticketList: [],
      checkedTicketList: [],
      queryForm: {
        empno: localStorage.getItem('empno'),
        departure: '',
        arrival: '',
        page: 1,
        limit: 6
      },
      transList: [],
      total: 0, 
      visible: false, 
      visible2: false,
      ticketForm: {} 
      ,travelForm: {} 
    };
  },
  methods: {
    handleSelectionChange(val) {
      this.checkedTicketList = val;
    },
    getTableData() {
      this.$http.post('/ticketList', this.queryForm).then(res => {
        this.ticketList = res.data.records;
        this.total = res.data.total;
      });
    },
    getTransList() {
    this.$http.get('/getTransportation').then(res => {
      this.transList = res.data.map(item => {
        const key = Object.keys(item)[0];
        return { id: key, name: item[key] };
      });
    });
  },
    getTransportName(id) {
      const transport = this.transList.find(trans => trans.id == id);
      return transport ? transport.name : '未知';
    },
    // 格式化日期为 "yyyy-MM-dd"
    formatDate(date) {
      if (!date) return '未知';
      const d = new Date(date);
      const year = d.getFullYear();
      const month = String(d.getMonth() + 1).padStart(2, '0');
      const day = String(d.getDate()).padStart(2, '0');
      return `${year}-${month}-${day}`;
    },
    handleSizeChange(val) {
      this.queryForm.limit = val;
      this.getTableData();
    },
    handleCurrentChange(val) {
      this.queryForm.page = val;
      this.getTableData();
    },
    openDialog() {
      this.ticketInfo = {}; 
      this.visible = true;
    },
    tableLoad(msg) {
      if (msg === 'success' || msg === true) {
        this.visible = false;
        this.$message.success('保存成功');
        this.getTableData();
      }
    },
    getOne() {
      if (this.checkedTicketList.length == 0) {
        this.$message.warning('请选择要修改的车票信息');
        return;
      }
      if (this.checkedTicketList.length > 1) {
        this.$message.warning('请选择一条数据进行修改');
        return;
      }
      let ticketId = this.checkedTicketList[0].ticketId;
      this.$http.get('/getTicketById?ticketId=' + ticketId).then(res => {
        this.ticketForm = res.data;
        this.visible = true;
      });
    },
    delTicket() {
      if (this.checkedTicketList.length == 0) {
        this.$message.warning('请选择要删除的数据');
        return;
      }

      this.$confirm('确定要删除选中的数据吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
          // 检查是否有已绑定的车票
          const hasBoundTickets = this.checkedTicketList.some(ticket => ticket.travelId != 0);
          if (hasBoundTickets) {
            this.$message.warning('选中的车票中包含已绑定差旅单的记录，无法删除');
            return;
          }
        const imageUrls = this.checkedTicketList
          .map(ticket => ticket.ticketImage)
          .filter(url => url && url.trim() != ''); // 排除无图片的情况

        
          //批量删除图片
          if (imageUrls.length > 0) {
            for (const url of imageUrls) {
              this.$http.post('/deleteTicketImage', { imageUrl: url }).then(res => {
                if (res.data.code !== 200) {
                    this.$message.error("删除图片失败")
                }
              })
              
            }
          }

          const ids = this.checkedTicketList.map(ticket => ticket.ticketId);
          await this.$http.post('/deleteTicketBatch', ids).then(res => {
            if (res.data.code !== 200) {
                    this.$message.error("删除车票失败")
                }
          })
          
          if (deleteRes.data === true || deleteRes.status === 200) {
            this.$message.success('删除成功');
            this.getTableData();
          } else {
            this.$message.error('车票删除失败');
          }
      }).catch(() => {
        this.$message({ type: 'info', message: '已取消删除' });
      });
    },
    async openTravelDetail(travelId) {
        this.$http.get('/getTravelById?travelId=' + travelId).then(res => {
          let travelBaseInfo = res.data
          if (!travelBaseInfo) {
          this.$message.warning('未找到对应的差旅单');
          return;
          } else {
            // 获取车票信息
          this.$http.get('/getTicketsByTravelId?travelId=' + travelId).then(res => {
            let tickets = Array.isArray(res.data) ? res.data : [];
            let validTickets = tickets.map(ticket => ({
              ...ticket,
              ticketId: ticket.ticketId
            }));
            this.travelForm = { ...travelBaseInfo, tickets: validTickets };
            this.visible2 = true;
          }).catch(err => {
            console.warn("获取车票信息失败:", err);
          });
          }
        })
    },
    // 单行修改
    handleEdit(row) {
      this.$http.get('/getTicketById?ticketId=' + row.ticketId).then(res => {
        this.ticketForm = res.data;
        this.visible = true;
      });
    },

  // 单行删除
  handleDelete(row) {
    this.$confirm('确定要删除车票及对应图片吗？', '警告', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(async () => {
      if (row.travelId != 0) {
        this.$message.warning('车票已绑定差旅单，无法删除');
        return;
      }
      if (row.ticketImage && row.ticketImage.trim() !== '') {
        const imgRes = await this.$http.post('/deleteTicketImage', { imageUrl: row.ticketImage });
        if (imgRes.data.code !== 200) {
          this.$message.error("照片删除失败")
        }
      }

      this.$http.post('/deleteTicketBatch', [row.ticketId]).then(res => {
        if (res.status === 200) {
        this.$message.success('删除成功');
        this.getTableData();
      } else {
        this.$message.error('删除失败');
      }
      })
    }).catch(() => {
      this.$message.info('已取消删除');
    });
  }
    
  },
  created() {
    this.getTableData();
    this.getTransList();
  }
};
</script>

<style scoped>
.ticket-list-container {
  max-width: 1200px;
  margin: 0 auto; /* Center the container */
  padding: 20px;
}

.el-row {
  margin-bottom: 20px;
}

.el-form-item {
  margin-right: 10px;
}

.el-button-group {
  display: flex;
  justify-content: flex-end;
}

.el-pagination {
  margin-top: 20px;
  text-align: center;
}

/* 新增按钮样式，确保可见 */
.flow-btn {
  color: #409eff; /* 蓝色文字，与Element UI主题一致 */
  padding: 0 10px;
}
</style>
